// 生成随机颜色
const randomInt = (min, max) =>
    Math.floor(Math.random() * (max - min) + 1 + min)
const randomColor = () =>
    `rgb(${randomInt(100, 255)},${randomInt(100, 255)},${randomInt(100, 255)})`

// 注册渐入观察
const revealSection = (entries, observer) => {
    const [entry] = entries
    if (!entry.isIntersecting) return
    entry.target.classList.remove('section--hidden')
    sectionsObserver.unobserve(entry.target)
}
const sectionsObserver = new IntersectionObserver(revealSection, {
    root: null,
    threshold: 0.1,
})

const allSelections = document.querySelectorAll('section')
allSelections.forEach((element) => {
    element.classList.add('section--hidden')
    element.style.backgroundColor = randomColor()
    element.style.transition = '.5s ease .5s'
    sectionsObserver.observe(element)
})

// 注册导航栏固定观察
const nav = document.querySelector('nav')
const stickyNav = (entries, observer) => {
    const [entry] = entries
    if (!entry.isIntersecting) {
        nav.classList.remove('sticky')
    } else {
        nav.classList.add('sticky')
    }
}
const stickyObserver = new IntersectionObserver(stickyNav, {
    root: null,
    threshold: 0,
})

// 装sections的容器
const container = document.querySelector('.container')
stickyObserver.observe(container)

// 注册图片懒加载观察
const imgs = document.querySelectorAll('img[data-src]')

const lazyImage = (entries, observer) => {
    const [entry] = entries
    if (!entry.isIntersecting) return
    entry.target.src = entry.target.dataset.src
    entry.target.addEventListener('load', () => {
        entry.target.classList.remove('lazy_img')
    })
    imgsObservers.unobserve(entry.target)
}
const imgsObservers = new IntersectionObserver(lazyImage, {
    root: null,
    threshold: 0.5,
})

imgs.forEach((element) => {
    imgsObservers.observe(element)
})
